<style lang="less" scoped>
.fixed-dialog-position.el-dialog__wrapper {
  position: absolute !important;
}
.el-dialog--center .el-dialog__body {
  padding: 7px 30px 54px 40px;
}

/deep/.el-form-item__label {
  padding-right: 0;
}

/deep/.el-tabs__nav-wrap::after {
  background-color: #fff;
}

/deep/ .white-head .el-dialog__header {

  background-color: white;
  color: #2b354a;
}

.dialog-title {
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  align-items: center;
}

.addBucketBox {
  button {
    width: 100px;
    height: 40px;
    background-color: #fff;
    border: 1px solid #DCDFE6;
    padding: 0;
  }
}

.el-table--border .el-table__fixed-body-wrapper {
  top: 41px !important;
}

/deep/.el-table__fixed {
  height: 100% !important;
}
</style>
<template>
  <div>
    <el-dialog v-el-drag-dialog class="fixed-dialog-position" :title="dialogTitle" :append-to-body='true' :visible.sync="AddSaveDeviceShow"
      :before-close="AddSaveDeviceClose" :close-on-click-modal="false" width="940px" top="3%" center>
      <div class="of">
        <div class="of">
          <div>
            <el-tabs v-model="activeName">
              <el-tab-pane :disabled="activeName !== '1' && dialogType !== 'add'" label="对象存储" name="1"></el-tab-pane>
              <el-tab-pane :disabled="activeName !== '0' && dialogType !== 'add'" label="文件存储" name="0"></el-tab-pane>
            </el-tabs>
          </div>
          <el-form label-position="right" :disabled="dialogType === 'view'" v-if="activeName === '1'"
            class="of fl pb25 mt15" style="width: 870px;" :model="objStorage" :rules="objStorageRules"
            ref="objStorageForm" key="objStorageForm">
            <div class="w100 mt10 clear_fixed">
              <el-form-item label="设备类型：" class="dib" label-width="70px" prop="oos_type">
                <el-select v-model="objStorage.oos_type" placeholder="请选择设备类型" size="medium" style="width:180px">
                  <el-option :value="0" label="亚马逊"></el-option>
                  <el-option :value="1" label="阿里云"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="设备名称：" class="dib" label-width="130px" prop="device_name">
                <el-input size="medium" placeholder="请输入设备名称" style="width:180px;" v-model="objStorage.device_name">
                </el-input>
              </el-form-item>
              <el-form-item label="访问地址：" class="dib" label-width="130px" prop="oos_access_url">
                <el-input size="medium" placeholder="请输入访问地址" style="width:180px;" v-model="objStorage.oos_access_url">
                </el-input>
              </el-form-item>
            </div>
            <div class="w100 mt10 clear_fixed">
              <el-form-item label="访问ID：" class="dib" label-width="70px" prop="oos_access_id">
                <el-input size="medium" placeholder="请输入访问ID" style="width:180px;" v-model="objStorage.oos_access_id">
                </el-input>
              </el-form-item>
              <el-form-item label="访问密钥：" class="dib" label-width="130px" prop="oos_access_key">
                <el-input :type="oos_access_keyBlur ? 'password' : 'text'" size="medium" placeholder="请输入访问密钥"
                  style="width:180px;" v-model="objStorage.oos_access_key" @focus="oos_access_keyBlur = false"
                  @blur="oos_access_keyBlur = true">
                </el-input>
              </el-form-item>
              <el-form-item label="桶参数：" class="dib" label-width="130px">
                <el-select v-model="bucketParams" placeholder="请选择桶参数" size="medium" style="width:180px">
                  <el-option value="single" label="单个桶"></el-option>
                  <el-option value="more" label="多个桶"></el-option>
                </el-select>
              </el-form-item>
            </div>
            <div class="w100 mt10 clear_fixed">
              <el-form-item label="系统名称：" class="dib" label-width="70px" prop="system_id">
                <el-select :disabled="group !== 'tenancy'" v-model="objStorage.system_id" placeholder="请选择系统名称"
                  size="medium" style="width:180px">
                  <el-option v-for="item in systemsLiteList" :key="item.id" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="机构名称：" class="dib" label-width="130px" prop="institution_id">
                <el-select :disabled="objStorageInstitutionsLiteList.length === 0" v-model="objStorage.institution_id"
                  placeholder="请选择机构名称" size="medium" style="width:180px">
                  <el-option v-for="item in objStorageInstitutionsLiteList" :key="item.id" :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="排序：" class="dib" label-width="130px" prop="sort_no">
                <el-input size="medium" placeholder="请输入排序" style="width:180px;" @input="objChangeInput"
                  v-model="objStorage.sort_no">
                </el-input>
              </el-form-item>
            </div>

            <!-- 单个桶 -->
            <div v-if="bucketParams === 'single'" class="w100 mt10 clear_fixed">
              <el-form-item label="桶名称：" label-width="70px" prop="oos_bucket_name">
                <el-input size="medium" placeholder="请输入桶名称" style="width:800px;" v-model="objStorage.oos_bucket_name">
                </el-input>
              </el-form-item>
            </div>
            <div v-if="bucketParams === 'single'" class="w100 mt10 clear_fixed">
              <el-form-item label="文件夹：" label-width="70px" prop="oos_folder_name">
                <el-input size="medium" placeholder="请输入文件夹" style="width:800px;" v-model="objStorage.oos_folder_name">
                </el-input>
              </el-form-item>
            </div>
            <!-- 多个桶 -->
            <div v-if="bucketParams === 'more'" class="clear_fixed addBucketBox mt15 mb10">
              <el-button @click="addBucket" class="fr" type="primary" plain><i
                  class="iconfont mr5">&#xe66e;</i>新增桶</el-button>
            </div>
            <el-table v-if="bucketParams === 'more'" :data="oos_bucket" border
              :header-cell-style="{ background: '#F5F5F5', color: '#333' }" highlight-current-row
              header-row-class-name="strong">
              <el-table-column label="序号" fixed="left" width="100">
                <template slot-scope="scope">
                  {{ scope.$index + 1 }}
                </template>
              </el-table-column>
              <el-table-column label="操作" fixed="left" width="120">
                <template slot-scope="scope">
                  <el-button title="查看" @click="viewDetail(scope.row, scope.$index)" type="primary" size="small"
                    class="w24 h24 lh24 nop"><i class="iconfont f18i thin">&#xe678;</i></el-button>
                  <el-button title="修改" @click="modifyDetail(scope.row, scope.$index)" type="primary" size="small"
                    class="w24 h24 lh24 nop"><i class="iconfont f18i thin">&#xe679;</i></el-button>
                  <el-button title="删除" @click="deleteFn(scope.$index)" type="danger" size="small"
                    class="w24 h24 lh24 nop"><i class="iconfont f18i thin">&#xe682;</i></el-button>
                </template>
              </el-table-column>
              <common-table :propData="propData"></common-table>
            </el-table>
            <!-- 新增桶begin -->
            <el-dialog width="800px" top="5%" :title="bucketDialogTitle" center :visible.sync="addBucketShow"
              :append-to-body='true'>
              <div class="of">
                <el-form class="of" label-position="right" :disabled="bucketDialogType === 'view'" :model="bucketData"
                  :rules="bucketDataRules" ref="bucketDataForm" key="bucketDataForm">
                  <div class="of fl pb25" style="width: 750px;">
                    <div class="w100 pb10 clear_fixed bbd">
                      <el-form-item label="存储条件：" class="dib" label-width="70px">
                        <el-checkbox class="ml10" checked disabled>检查日期</el-checkbox>
                      </el-form-item>
                    </div>
                    <div class="mt25 mb15">桶信息</div>
                    <div class="w100 pb10 clear_fixed">
                      <el-form-item label="桶名称：" label-width="70px" prop="bucket_name">
                        <el-input size="medium" placeholder="请输入桶名称" v-model="bucketData.bucket_name" clearable>
                        </el-input>
                      </el-form-item>
                    </div>
                    <div class="w100 pb10 clear_fixed">
                      <el-form-item label="文件夹：" label-width="70px" prop="folder_name">
                        <el-input size="medium" placeholder="请输入文件夹" v-model="bucketData.folder_name" clearable>
                        </el-input>
                      </el-form-item>
                    </div>
                    <div class="w100 pb10 clear_fixed">
                      <el-form-item label="检查日期：" class="dib" label-width="70px" prop="bucketDataCheckDate">
                        <el-date-picker v-model="bucketData.bucketDataCheckDate" type="daterange" size="medium"
                          align="right" unlink-panels range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
                          value-format="yyyy-MM-dd HH:mm:ss" :picker-options="addBucketPickerOptions">
                        </el-date-picker>
                      </el-form-item>
                    </div>
                  </div>
                </el-form>
                <div slot="footer" class="dialog-footer mt20 fr">
                  <el-button @click="addBucketShow = false" size="small" class="mr20">关 闭</el-button>
                  <el-button v-if="bucketDialogType !== 'view'" @click="AddBucketSave('bucketDataForm')" type="primary"
                    size="small">保 存</el-button>
                </div>
              </div>
            </el-dialog>
            <!-- 新增桶end -->
            <div class="w100 mt10 clear_fixed">
              <el-button v-if="objStorage.device_type === 1 && objStorage.oos_is_stopped === 0 && dialogType !== 'add'"
                @click="switchFn('objStorage', 'oos_is_stopped')" type="danger" size="small" plain><i
                  class="iconfont mr5">&#xe67d;</i>停用</el-button>
              <el-button v-if="objStorage.device_type === 1 && objStorage.oos_is_stopped === 1 && dialogType !== 'add'"
                @click="switchFn('objStorage', 'oos_is_stopped')" type="success" size="small" plain><i
                  class="iconfont mr5">&#xe67d;</i>启用</el-button>
            </div>
          </el-form>
          <el-form label-position="right" :disabled="dialogType === 'view'" v-if="activeName === '0'"
            class="of fl pb25 mt15" style="width: 870px;" :model="fileStorage" :rules="fileStorageRules"
            ref="fileStorageForm" key="fileStorageForm">
            <div class="w100 mt10 clear_fixed">
              <el-form-item label="设备名称：" class="dib" label-width="70px" prop="device_name">
                <el-input size="medium" placeholder="请输入设备名称" style="width:180px;" v-model="fileStorage.device_name">
                </el-input>
              </el-form-item>
              <el-form-item label="存储路径：" class="dib" label-width="130px" prop="local_storage_path">
                <el-input size="medium" placeholder="请输入存储路径" style="width:180px;"
                  v-model="fileStorage.local_storage_path">
                </el-input>
              </el-form-item>
              <el-form-item label="实际路径：" class="dib" label-width="130px" prop="local_storage_net_path">
                <el-input size="medium" placeholder="请输入实际路径" style="width:180px;"
                  v-model="fileStorage.local_storage_net_path">
                </el-input>
              </el-form-item>
            </div>
            <div class="w100 mt10 clear_fixed">
              <el-form-item label="用户名称：" class="dib" label-width="70px" prop="local_access_user">
                <el-input size="medium" placeholder="请输入用户名称" style="width:180px;"
                  v-model="fileStorage.local_access_user">
                </el-input>
              </el-form-item>
              <el-form-item label="访问密码：" class="dib" label-width="130px" prop="local_access_password">
                <el-input type="password" size="medium" placeholder="请输入访问密码" style="width:180px;"
                  v-model="fileStorage.local_access_password">
                </el-input>
              </el-form-item>
              <el-form-item label="预留空间：" class="dib" label-width="130px" prop="local_reserved_space">
                <el-input-number style="width: 100px" size="medium" v-model="fileStorage.local_reserved_space"
                  controls-position="right" :min="1"></el-input-number>
                <span class="ml20">GB</span>
              </el-form-item>
            </div>
            <div class="w100 mt10 clear_fixed">
              <el-form-item label="系统名称：" class="dib" label-width="70px" prop="system_id">
                <el-select :disabled="group !== 'tenancy'" v-model="fileStorage.system_id" placeholder="请选择系统名称"
                  size="medium" style="width:180px">
                  <el-option v-for="item in systemsLiteList" :key="item.id" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="机构名称：" class="dib" label-width="130px" prop="institution_id">
                <el-select :disabled="fileStorageInstitutionsLiteList.length === 0" v-model="fileStorage.institution_id"
                  placeholder="请选择机构名称" size="medium" style="width:180px">
                  <el-option v-for="item in fileStorageInstitutionsLiteList" :key="item.id" :label="item.name"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="映射路径：" class="dib" label-width="130px" prop="local_storage_mapping_path">
                <el-input size="medium" placeholder="请输入映射路径" style="width:180px;"
                  v-model="fileStorage.local_storage_mapping_path">
                </el-input>
              </el-form-item>
            </div>
            <div class="w100 mt10 clear_fixed">
              <el-form-item label="排序：" class="dib" label-width="70px" prop="sort_no">
                <el-input size="medium" placeholder="请输入排序" style="width:180px;" @input="fileChangeInput"
                  v-model="fileStorage.sort_no">
                </el-input>
              </el-form-item>
            </div>
            <div class="w100 mt10 clear_fixed">
              <el-button
                v-if="fileStorage.device_type !== 1 && fileStorage.local_is_stopped === 0 && dialogType !== 'add'"
                @click="switchFn('fileStorage', 'local_is_stopped')" type="danger" size="small" plain><i
                  class="iconfont mr5">&#xe67d;</i>停用</el-button>
              <el-button
                v-if="fileStorage.device_type !== 1 && fileStorage.local_is_stopped === 1 && dialogType !== 'add'"
                @click="switchFn('fileStorage', 'local_is_stopped')" type="success" size="small" plain><i
                  class="iconfont mr5">&#xe67d;</i>启用</el-button>
            </div>
          </el-form>
        </div>
        <div slot="footer" class="dialog-footer mt20 fr">
          <el-button @click="AddSaveDeviceClose" size="small" class="mr20">关 闭</el-button>
          <el-button v-if="dialogType !== 'view'" @click="AddSaveDevicePreSave" type="primary" size="small">保
            存</el-button>
        </div>
      </div>
    </el-dialog>
    <div class="white-head">
      <el-dialog title="提示" :visible.sync="innerVisible" width="30%" :before-close="handleClose">
        <div slot="title" class="dialog-title fff">
          <i class="iconfont clr_warn" style="font-size: 26px;">&#xe680;</i>
          <span class="f16 ml10">
            提示
          </span>
        </div>
        <span v-if="offlineModeAppointCapacity">
          <br />
          <span v-if="offlineModeAppointCapacity&&nearlineModeAppointCapacity">1、</span>在线设备/近线设备存在已启用的对象存储设备时，删除策略只可设置为指定天数，请修改删除策略
        </span>
        <span v-if="nearlineModeAppointCapacity">
          <br />
          <span v-if="offlineModeAppointCapacity&&nearlineModeAppointCapacity">2、</span>在线设备存在已启用的对象存储设备时，近线策略只可设置为指定天数，请修改近线策略
        </span>
        <span slot="footer" class="dialog-footer">
          <el-button @click="innerVisible = false">取 消</el-button>
          <el-button type="primary" @click="AddSaveDeviceSaveAndOpenSaveStrategy">
            {{ addButtonTitle }}</el-button>
        </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import CommonTable from '@/components/common/CommonTable' // 表格
import { validURL, validIP, validPath } from '@/utils/validate'
import { mapGetters } from 'vuex'

export default {
  data() {
    let requiredValidator = function (tip) {
      return (rule, value, callback) => {
        if (value === '') {
          callback(new Error(tip))
        } else {
          callback()
        }
      }
    }
    let isRequiredValidator = (tip) => {
      return (rule, value, callback) => {
        if (this.device_category === 0) { // 在线设备
          callback()
        } else if (this.device_category === 1) { // 近线设备
          if (value === '') {
            callback(new Error(tip))
          } else {
            callback()
          }
        } else {
          callback()
        }
      }
    }
    let urlValidator = (rule, value, callback) => {
      if (value !== '') {
        if (validURL(value) || validIP(value)) {
          callback()
        } else {
          callback(new Error('访问地址格式错误'))
        }
      } else {
        callback(new Error('请输入访问地址'))
      }
    }
    let bucketValidator = (rule, value, callback) => {
      // let { activeName, bucketParams } = this._parentVnode.child // 此处只能通过这种方式获取this
      if (this.activeName === '1' && this.bucketParams === 'single' && value === '') {
        callback(new Error('请输入桶名称'))
      } else {
        callback()
      }
    }
    let folderPathValidator = (rule, value, callback) => {
      // let { activeName, bucketParams } = this._parentVnode.child // 此处只能通过这种方式获取this
      if (this.activeName === '1' && this.bucketParams === 'single') {
        if (value !== '') {
          if (validPath(value)) {
            callback()
          } else {
            callback(new Error('文件夹路径输入错误'))
          }
        } else {
          callback(new Error('请输入文件夹'))
        }
      } else {
        callback()
      }
    }
    let savePathValidator = (rule, value, callback) => {
      if (this.activeName === '0') {
        if (value !== '') {
          if (validPath(value)) {
            callback()
          } else {
            callback(new Error('存储路径输入错误'))
          }
        } else {
          callback(new Error('请输入存储路径'))
        }
      } else {
        callback()
      }
    }
    let actualPathValidator = (rule, value, callback) => {
      if (this.activeName === '0') {
        if (value !== '') {
          if (validPath(value)) {
            callback()
          } else {
            callback(new Error('存储路径输入错误'))
          }
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    // let mappingPathValidator = (rule, value, callback) => {
    //   if(this.activeName === '0') {
    //     if(value !== '') {
    //       if(validPath(value)) {
    //         callback()
    //       }else {
    //         callback(new Error('映射路径输入错误'))
    //       }
    //     }else {
    //       callback(new Error('请输入映射路径'))
    //     }
    //   }else {
    //     callback()
    //   }
    // }
    let reserveSpaceIptNumValidator = (rule, value, callback) => {
      if (this.activeName === '0') {
        if (value === undefined) {
          callback(new Error('请输入'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    let pathValidator = (rule, value, callback) => {
      if (value !== '') {
        if (validPath(value)) {
          return callback()
        } else {
          callback(new Error('文件夹路径输入错误'))
        }
      } else {
        callback(new Error('请输入文件夹'))
      }
    }
    let dateValidator = (rule, value, callback) => {
      if (value === null) {
        callback(new Error('请选择检查日期'))
      } else {
        callback()
      }
    }
    return {
      dialogTitle: '新增存储设备',
      activeName: '1',
      bucketParams: 'single', // 桶参数
      id: 0,
      objStorage: {
        device_name: '',
        device_type: 1,
        device_category: '',
        oos_type: '',
        oos_access_url: '',
        oos_access_id: '',
        oos_access_key: '',
        oos_bucket_number: 1,
        oos_bucket_name: '',
        oos_folder_name: '',
        system_id: '',
        system_name: '',
        institution_id: '',
        institution_name: '',
        local_is_stopped: 0,
        oos_is_stopped: 0,
        sort_no: ''
      },
      oos_access_keyBlur: true,
      objStorageRules: {
        oos_type: [{
          trigger: 'blur',
          validator: requiredValidator('请选择设备类型')
        }],
        device_name: [{
          trigger: 'blur',
          validator: requiredValidator('请输入设备名称')
        }],
        // oos_access_url: [{
        //   trigger: 'blur',
        //   validator: urlValidator
        // }],
        oos_access_id: [{
          trigger: 'blur',
          validator: requiredValidator('请输入访问ID')
        }],
        oos_access_key: [{
          trigger: 'blur',
          validator: requiredValidator('请输入访问密钥')
        }],
        oos_bucket_name: [{
          trigger: 'blur',
          validator: bucketValidator
        }],
        oos_folder_name: [{
          trigger: 'blur',
          validator: requiredValidator('请输入文件夹')
        }],
        // tenantId: [{
        //   trigger: 'blur',
        //   validator: requiredValidator('请选择客户名称')
        // }],
        // institution_id: [{
        //   trigger: 'blur',
        //   validator: requiredValidator('请选择机构名称')
        // }]
        sort_no: [{
          trigger: 'blur',
          validator: requiredValidator('请输入排序')
        }]
      },
      // 多个桶列表
      oos_bucket: [],
      fileStorage: {
        device_name: '',
        device_type: 1,
        device_category: '',
        local_storage_path: '',
        local_storage_net_path: '',
        local_storage_mapping_path: '',
        local_access_user: '',
        local_access_password: '',
        local_reserved_space: 1,
        local_is_stopped: '',
        system_id: '',
        system_name: '',
        institution_id: '',
        institution_name: '',
        sort_no: ''
      },
      fileStorageRules: {
        device_name: [{
          trigger: 'blur',
          validator: requiredValidator('请输入设备名称')
        }],
        local_storage_path: [{
          trigger: 'blur',
          validator: requiredValidator('请输入存储路径')
          // validator: savePathValidator
        }],
        local_storage_net_path: [{
          trigger: 'blur',
          validator: actualPathValidator
        }],
        local_storage_mapping_path: [{
          trigger: 'blur',
          validator: requiredValidator('请输入映射路径')
        }],
        // local_access_user: [{
        //   trigger: 'blur',
        //   validator: isRequiredValidator('请输入用户名称')
        // }],
        // local_access_password: [{
        //   trigger: 'blur',
        //   validator: isRequiredValidator('请输入访问密码')
        // }],
        local_reserved_space: [{
          trigger: 'blur',
          validator: reserveSpaceIptNumValidator
        }],
        // tenantId: [{
        //   trigger: 'blur',
        //   validator: requiredValidator('请选择客户名称')
        // }],
        // institution_id: [{
        //   trigger: 'blur',
        //   validator: requiredValidator('请选择机构名称')
        // }]
        sort_no: [{
          trigger: 'blur',
          validator: requiredValidator('请输入排序')
        }]
      },
      propData: [
        {
          prop: 'bucket_name',
          label: '桶名称'
        },
        {
          prop: 'folder_name',
          label: '文件夹'
        }
      ],
      // 新增桶
      bucketDialogTitle: '新增桶',
      bucketDialogType: 'add',
      currentBucketIndex: '',
      addBucketShow: false,
      addBucketPickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            picker.$emit('pick', [start, end])
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            picker.$emit('pick', [start, end])
          }
        }]
      },
      bucketData: {
        bucket_name: '',
        folder_name: '',
        begin_study_date_time: '',
        end_study_date_time: '',
        bucketDataCheckDate: null
      },
      bucketDataRules: {
        bucket_name: [{
          trigger: 'blur',
          validator: requiredValidator('请输入桶名称')
        }],
        folder_name: [{
          trigger: 'blur',
          validator: pathValidator
        }],
        bucketDataCheckDate: [{
          trigger: 'blur',
          validator: dateValidator
        }]
      },
      systemsLiteList: [], // 系统名称
      objStorageInstitutionsLiteList: [], // 机构名称
      fileStorageInstitutionsLiteList: [], // 机构名称
      isInstitutionsClear: 1, // 打开dialog后第一次改变系统名称,不清空机构名称的值,后面每次都清空,dialogType为add时,从第一次开始就清空机构名称的值
      innerVisible: false,//是否显示提示框（关于存储策略）
      innerVisibleShouldShow: false,//是否需要显示提示框关于存储策略）
      shouldOpenSetSaveStrategy: false,//是否打开存储策略弹框
      nearlineModeAppointCapacity:false,//近线是否指定容量
      offlineModeAppointCapacity:false,//删除是否指定容量
      addButtonTitle:'新增设备并修改策略',
      saveStrategyData:{},

    }
  },
  props: ['AddSaveDeviceShow', 'rowId', 'dialogType', 'device_category', 'tenantOptions', 'institutionList'],
  components: {
    CommonTable
  },
  computed: {
    ...mapGetters(['group', 'systemid'])
  },
  watch: {
    activeName: {
      handler(newVal) {
        this.objStorage.device_type = Number(newVal)
        this.fileStorage.device_type = Number(newVal)
        console.log(newVal)
        console.log(this.fileStorage.device_type)
      },
      immediate: true
    },
    device_category: {
      handler(newVal) {
        this.objStorage.device_category = newVal
        this.fileStorage.device_category = newVal
      },
      immediate: true
    },
    'bucketData.bucketDataCheckDate': {
      handler(newVal) {
        this.bucketData.begin_study_date_time = newVal ? newVal[0] : ''
        this.bucketData.end_study_date_time = newVal ? newVal[1] : ''
      },
      deep: true,
      immediate: true
    },
    dialogType(newVal) { // 修改弹窗标题
      this.dialogTitle = newVal === 'add' ? '新增存储设备' : newVal === 'view' ? '查看' : newVal === 'modify' ? '修改' : ''
      if (newVal === 'add') {
        // 重置数据
        // this.resetData()
        if (this.tenantOptions.length !== 0) {
          this.objStorage.tenantId = this.tenantOptions[0]['id']
          this.fileStorage.tenantId = this.tenantOptions[0]['id']
          console.log(this.objStorage.tenantId)
        }
      }
    },
    bucketDialogType(newVal) {
      this.bucketDialogTitle = newVal === 'add' ? '新增桶' : newVal === 'view' ? '查看' : newVal === 'modify' ? '修改' : ''
      if (newVal === 'add') {
        // 重置数据
        this.bucketData = this.$options.data().bucketData

      }
    },
    AddSaveDeviceShow(newVal) {
      this.shouldOpenSetSaveStrategy = false

      console.log(this.fileStorage.device_type)
      console.log(this.objStorage.device_type)
      this.$nextTick(() => {
        if (newVal) {
                //获取存储策略设置数据
      this.getSaveStrategy()
          // // 这里要改成 this.group
          if (this.group === 'dept') { // 科室角色
            this.$nextTick(() => {
              this.objStorage.system_id = this.systemid
              this.fileStorage.system_id = this.systemid
            })
          }
          if (this.activeName === '1') {
            this.$nextTick(() => {
              this.$refs['objStorageForm'].resetFields();
            })
          } else if (this.activeName === '0') {
            this.$nextTick(() => {
              this.$refs['fileStorageForm'].resetFields();
            })
          }
          if (newVal && this.rowId !== 0) {
            this.getSaveDevice(this.rowId)
          } else {
            this.objStorage = this.$options.data().objStorage
            this.fileStorage = this.$options.data().fileStorage
            this.oos_bucket = this.$options.data().oos_bucket
          }
          this.getSystemsLiteList() // 获取系统名称
        } else {
          this.isInstitutionsClear = 1
        }
      })
    },
    'fileStorage.device_type': {
      handler: function (newVal) {
        console.log(newVal)
      },
      immediate: true
    },
    'objStorage.system_id': {
      handler: function (newVal) {
        if (newVal === '') {
          this.objStorage.system_name = ''
        } else {
          this.systemsLiteList.forEach((ele) => {
            if (ele.id === newVal) {
              this.objStorage.system_name = ele.name
            }
          })
          if (this.dialogType === 'add') {
            this.objStorage.institution_id = ''
          }
          if (this.dialogType === 'modify' && this.isInstitutionsClear === 2) {
            this.objStorage.institution_id = ''
          }
          this.getInstitutionsLiteList(newVal, 'objStorageInstitutionsLiteList') // 获取机构名称
        }
      },
      immediate: true
    },
    'objStorage.institution_id': {
      handler: function (newVal) {
        if (newVal === '') {
          this.objStorage.institution_name = ''
        } else {
          this.objStorageInstitutionsLiteList.forEach((ele) => {
            if (ele.id === newVal) {
              this.objStorage.institution_name = ele.name
            }
          })
        }
      }
    },
    'fileStorage.system_id': {
      handler: function (newVal) {
        if (newVal === '') {
          this.fileStorage.system_name = ''
        } else {
          this.systemsLiteList.forEach((ele) => {
            if (ele.id === newVal) {
              this.fileStorage.system_name = ele.name
            }
          })
          if (this.dialogType === 'add') {
            this.fileStorage.institution_id = ''
          }
          if (this.dialogType === 'modify' && this.isInstitutionsClear === 2) {
            this.fileStorage.institution_id = ''
          }
          this.getInstitutionsLiteList(newVal, 'fileStorageInstitutionsLiteList') // 获取机构名称
        }
      },
      immediate: true
    },
    'fileStorage.institution_id': {
      handler: function (newVal) {
        if (newVal === '') {
          this.fileStorage.institution_name = ''
        } else {
          this.fileStorageInstitutionsLiteList.forEach((ele) => {
            if (ele.id === newVal) {
              this.fileStorage.institution_name = ele.name
            }
          })
        }
      }
    },
  },
  methods: {
    handleClose(){
      this.innerVisible = false
    },
    objChangeInput() {
      const rules = /^[1-9][0-9]*$/
      if (!rules.test(this.objStorage.sort_no)) {
        this.objStorage.sort_no = null
      }
    },
    fileChangeInput() {
      const rules = /^[1-9][0-9]*$/
      if (!rules.test(this.fileStorage.sort_no)) {
        this.fileStorage.sort_no = null
      }
    },
    AddSaveDeviceClose() {

      this.$emit('AddSaveDeviceClose', this.shouldOpenSetSaveStrategy)
    },
    AddBucketSave(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let bucketData1 = Object.assign({}, this.bucketData)
          delete bucketData1.bucketDataCheckDate
          if (this.bucketDialogType === 'add') {
            this.oos_bucket.push(bucketData1)
          } else if (this.bucketDialogType === 'modify') {
            this.oos_bucket.splice(this.currentBucketIndex, 1, bucketData1)
          }
          this.bucketData = this.$options.data().bucketData
          this.addBucketShow = false
        } else {
          return false
        }
      })
    },
    addBucket() {
      this.addBucketShow = true
      this.bucketDialogType = 'add'
      this.currentBucketIndex = ''
    },
    viewDetail(rowData, index) {
      this.addBucketShow = true
      this.bucketDialogType = 'view'
      this.currentBucketIndex = index
      Object.assign(this.bucketData, rowData)
      this.bucketData.bucketDataCheckDate = [rowData.begin_study_date_time, rowData.end_study_date_time]
    },
    modifyDetail(rowData, index) {
      this.addBucketShow = true
      this.bucketDialogType = 'modify'
      this.currentBucketIndex = index
      Object.assign(this.bucketData, rowData)
      this.bucketData.bucketDataCheckDate = [rowData.begin_study_date_time, rowData.end_study_date_time]
    },
    deleteFn(index) {
      this.$confirm('确定删除吗?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.oos_bucket.splice(index, 1)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //获取存储策略信息
    async getSaveStrategy() {
      
      const res = await this.$pacsApi.pacsApi.getSaveStrategy()
      const { code, data } = res
      if (code === 0) {
        this.saveStrategyData = data
        //在线设备添加对象存储时
        this.nearlineModeAppointCapacity = data.nearline_enable === 1  && data.nearline_mode === 1 && this.device_category=== 0 
         //删除策略已开启且指定容量时--添加对象存储时
        this.offlineModeAppointCapacity = data.offline_enable === 1 && data.offline_mode === 1

      } else {
        this.nearlineModeAppointCapacity = false
        this.offlineModeAppointCapacity = false
      }
      
      this.innerVisibleShouldShow = this.nearlineModeAppointCapacity || this.offlineModeAppointCapacity
      this.addButtonTitle = this.dialog_type === 'add'?'新增设备并修改策略':'保存并修改策略'
    },
    //打开存储策略弹框
    AddSaveDeviceSaveAndOpenSaveStrategy() {
      this.shouldOpenSetSaveStrategy = true
      this.innerVisible = false
      this.AddSaveDeviceSave()
    },
    //预保存
    AddSaveDevicePreSave() {

      // 对象存储时需要判断是否删除策略开启且设置为指定容量 
      //删除策略已开启且指定容量时，需弹框提示修改删除策略
      let formName = this.activeName === '1' ? 'objStorageForm' : 'fileStorageForm'
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.activeName === '1' && this.innerVisibleShouldShow) {
            //对象存储
            this.innerVisible = true
          } else {
            this.AddSaveDeviceSave()
          }
        } else {
          return false
        }
      })



    }
    ,
    AddSaveDeviceSave() {

      // let formName = this.activeName === '1' ? 'objStorageForm' : 'fileStorageForm'
      let device_type = this.activeName === '1' ? 1 : 0
      // this.$refs[formName].validate((valid) => {
        // if (valid) {
          let submitData = {}
          if (this.activeName === '1') { // 对象存储
            if (this.bucketParams === 'single') {
              this.objStorage.oos_bucket_number = 1
              submitData = Object.assign(submitData, this.objStorage)
              submitData.device_type = device_type // 确保device_type正确
              if (this.dialogType === 'modify') {
                this.updateSaveDevice(submitData, this.id)
              } else if (this.dialogType === 'add') {
                submitData.device_category = this.device_category
                this.addSaveDevice(submitData)
              }
            } else if (this.bucketParams === 'more') {
              this.objStorage.oos_bucket_number = this.oos_bucket.length
              submitData = { ...this.objStorage, oos_bucket: this.oos_bucket }
              delete submitData.oos_bucket_name
              delete submitData.oos_folder_name
              submitData.device_category = this.device_category
              submitData.device_type = device_type // 确保device_type正确
              this.addSaveDevice(submitData)
            }
          } else if (this.activeName === '0') { // 文件存储
            submitData = this.fileStorage
            submitData.device_type = device_type // 确保device_type正确
            if (this.dialogType === 'modify') {
              this.updateSaveDevice(submitData, this.id)
            } else if (this.dialogType === 'add') {
              console.log(this.fileStorage.device_type)
              submitData.device_category = this.device_category
              this.addSaveDevice(submitData)
            }
          }
        // } else {
        //   return false
        // }
      // })
    },
    async addSaveDevice(submitData) {
      const res = await this.$pacsApi.pacsApi.addSaveDevice(submitData)
      const { code, msg } = res
      if (code === 0) {
        this.$message({
          type: 'success',
          message: msg
        })
        this.AddSaveDeviceClose()
        this.resetData()
        // 刷新列表
        this.$emit('refreshList')
      } else {
        this.$message.error(msg)
      }
    },
    async updateSaveDevice(submitData, id) {
      const res = await this.$pacsApi.pacsApi.updateSaveDevice(submitData, id)
      const { code, msg } = res
      if (code === 0) {
        this.$message({
          type: 'success',
          message: msg
        })
        this.AddSaveDeviceClose()
        // 刷新列表
        this.$emit('refreshList')
      } else {
        this.$message.error(msg)
      }
    },
    async getSaveDevice(id) {
      const res = await this.$pacsApi.pacsApi.getSaveDevice(id)
      const { code, data } = res
      if (code === 0) {
        if (data.device_type === 1) { // 对象存储
          this.nearlineModeAppointCapacity = this.saveStrategyData.nearline_enable === 1  && this.saveStrategyData.nearline_mode === 1 && data.device_category=== 0 
          this.innerVisibleShouldShow = this.nearlineModeAppointCapacity || this.offlineModeAppointCapacity

          this.activeName = '1'
          this.id = data.id
          for (const key in data) {
            if (Object.keys(this.objStorage).includes(key)) {
              this.objStorage[key] = data[key]
            }
          }
          if (data.oos_bucket_number === 1) { // 单个桶
            this.bucketParams = 'single'
          } else if (data.oos_bucket_number > 1) { // 多个桶
            this.bucketParams = 'more'
            this.oos_bucket = data.oos_bucket
          }
        } else if (data.device_type === 0) { // 文件存储
          this.activeName = '0'
          this.id = data.id
          for (const key in data) {
            if (Object.keys(this.fileStorage).includes(key)) {
              this.fileStorage[key] = data[key]
            }
          }
        }
        this.$nextTick(() => {
          this.isInstitutionsClear = 2
        })
      }
    },
    // 重置data数据
    resetData() {
      Object.assign(this.$data, this.$options.data())
    },
    switchFn(storageType, isStopType) {
      let tip = ''
      let obj = ''
      if (this[storageType][isStopType] === 1) {
        tip = '启用'
        obj = {
          is_stopped: 0
        }
      } else {
        tip = '停用'
        obj = {
          is_stopped: 1
        }
      }
      this.$confirm(`确定${tip}存储设备?`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.switchSaveDeviceState(obj, this.id)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消'
        })
      })
    },
    async switchSaveDeviceState(data, id) {
      const res = await this.$pacsApi.pacsApi.switchSaveDeviceState(data, id)
      const { code, msg } = res
      if (code === 0) {
        this.$message({
          type: 'success',
          message: msg
        })
        // 重新获取数据
        this.getSaveDevice(this.rowId)
        // 刷新列表
        this.$emit('refreshList')
      }
    },
    async getSystemsLiteList() { // 获取系统名称
      let res = await this.$pacsApi.pacsApi.getSystemsLiteList({ type: 1 })
      let { code, data } = res
      if (code === 0) {
        this.systemsLiteList = data
      }
    },
    // objStorageSystemNameChange(val) {
    //   this.getInstitutionsLiteList(val, 'objStorageInstitutionsLiteList')
    //   this.objStorage.institution_id = ''
    //   this.objStorage.institution_name = ''
    // },
    // fileStorageSystemNameChange(val) {
    //   console.log('触发了')
    //   this.getInstitutionsLiteList(val, 'fileStorageInstitutionsLiteList')
    //   this.fileStorage.institution_id = ''
    //   this.fileStorage.institution_name = ''
    // },
    async getInstitutionsLiteList(val, storageType) {
      if (val) {
        // // 转换成系统ID
        // let system_id = ''
        // this.systemsLiteList.forEach((ele) => {
        //   if(ele.name === val) {
        //     system_id = ele.id
        //   }
        // })
        let res = await this.$pacsApi.pacsApi.getInstitutionsLiteList({ system_id: val })
        let { code, data } = res
        if (code === 0) {
          this[storageType] = data
        }
      }
    },
  },
  mounted() {

  }
}
</script>
